package com.dayu.tcp.common.util;

import lombok.NonNull;
import lombok.SneakyThrows;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author yehangtech
 * @date 2024/4/5
 * @description Object工具类
 */
public class ObjUtil {
    private ObjUtil() {
    }

    /**
     * 对象转数组
     *
     * @param obj
     * @return 字节流
     */
    @SneakyThrows
    public static byte[] toByteArray(Object obj) {
        byte[] ret;
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            oos.writeObject(obj);
            oos.flush();
            ret = bos.toByteArray();
            return ret;
        }
    }

    /**
     * byte数组转对象
     *
     * @param bytes
     * @return Object
     */
    @SneakyThrows
    public static Object toObject(@NonNull byte[] bytes) {
        Object ret;
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
        ) {
            ret = ois.readObject();
            return ret;
        }
    }

    public static int bytes2Int(byte[] bytes) {
        int ret;
        ret = bytes[0] & 0xff;
        ret = ret << 8 | bytes[1] & 0xff;
        ret = ret << 8 | bytes[2] & 0xff;
        ret = ret << 8 | bytes[3] & 0xff;
        return ret;
    }

    public static byte[] int2Bytes(int num) {
        byte[] ret = new byte[4];
        ret[0] = (byte) (num >> 24);
        ret[1] = (byte) (num >> 16);
        ret[2] = (byte) (num >> 8);
        ret[3] = (byte) num;
        return ret;
    }
}
